/* EjectManager的逻辑是
一层一层的向上叠加
*/

cc.Class({
    extends: cc.Component,

    properties: {
    },

    onLoad(){
        this.currentPanel = null;
        this.panelNames = [];

        this.panels = [];
    },

    clearNode(){
        this.node.destroyAllChildren();
        this.panels = [];
        this.panelNames = [];
    },

    getTopUI(){
        return this.currentPanel;
    },

    pushUI(name,script,options){
        this.panelNames.push({name:name,script:script,options:options});
        return this._updateEject()
    },

    popUI(){
        var self =this;

        if(this.currentPanel != null){
            this.currentPanel.emit('onExitWindowBegin');
            this.currentPanel.runAction(cc.sequence(cc.delayTime(0.3),cc.callFunc(function(node){
                node.emit('onExitWindowEnd');
                node.destroy();
            })))
            this.panels.pop();
        }
        if(this.panels.length >0){
            this.currentPanel = this.panels[this.panels.length-1];
            this.currentPanel.emit('onWindowFocus');
        } else {
            this.currentPanel = null
            global.UIMgr.postFocus();
        }
    },

    _updateEject(){
        if(this.panelNames.length > 0){
            var base = this.panelNames.pop();
            var node = global.Loader.getInstantiate(base.name)
            // setTimeout(()=>{ //延时一帧，保证所有方法都初始化完成
            //     node.emit('onEnterWindowBegin');
            // },10)
            this.scheduleOnce(()=>{
                node.emit('onEnterWindowBegin');
            },0.01)
            this.currentPanel = node;
            this.node.addChild(node);
            this.panels.push(node);
            this._updateEject();

            if(base.script && typeof(base.script) == 'string'){
                if(base.options){
                    node.getComponent(base.script).setOptions(base.options)
                }
            } else if(typeof(base.script) == 'object'){
                var _js = base.name.substring(base.name.lastIndexOf('/')+1)
                node.getComponent(_js).setOptions(base.script)
            }
            return node;
        }
        return null;
    },
    showToast(content){
        var node = global.Loader.getInstantiate('Eject/Toast')
        node.getComponentInChildren(cc.Label).string = content
        this.node.addChild(node);
        node.runAction(cc.sequence(cc.delayTime(1.5),cc.spawn(cc.moveBy(0.5,cc.v2(0,40)),cc.fadeOut(0.5))))
    },
    showModal(options){
        let eject = global.EJMgr.pushUI('Eject/Alert');
        eject.getComponent('Alert').setOptions(options)
    }
});
